package com.itheima.controller.system;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.system.Dept;
import com.itheima.domain.system.Role;
import com.itheima.domain.system.SystemSet;
import com.itheima.domain.system.User;
import com.itheima.utils.Log4jTest;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

/**
 * create by guowenlaing
 * 2021/10/17
 * 用户的增删改查
 */
@WebServlet(urlPatterns = "/system/user")
public class UserServlet extends BaseServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 获取所有部门
        List<Dept> deptList = deptService.findAll();
        request.setAttribute("deptList",deptList);
        //获取参数
        String operation = request.getParameter("operation");
        if ("list".equals(operation)) {
            this.list(request, response);
        } else if ("toAdd".equals(operation)) {
            this.toAdd(request, response);
        } else if ("save".equals(operation)) {
            this.save(request, response);
        } else if ("toEdit".equals(operation)) {
            this.toEdit(request, response);
        } else if ("edit".equals(operation)) {
            this.edit(request, response);
        } else if ("delete".equals(operation)) {
            this.delete(request, response);
        } else if ("userRoleList".equals(operation)) {
            userRoleList(request, response);
        } else if ("updateRole".equals(operation)) {
            updateRole(request, response);
        } else if ("conditionSearch".equals(operation)) {
            conditionSearch(request, response);
        }
    }

    // 跳转到添加界面
    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 查询所有部门
        List<Dept> deptList = deptService.findAll();
        request.setAttribute("deptList", deptList);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/system/user/add.jsp").forward(request, response);
    }

    // 添加用户
    private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String userName = request.getParameter("userName");
        String deptId = request.getParameter("deptId") == "" ? null : request.getParameter("deptId");
        // 通过deptId，查询到dept，然后获取deptName
        String deptName = null;
        if (deptId != null) {
            deptName = deptService.findById(deptId).getDeptName();
        }
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String state = request.getParameter("state");
        String telephone = request.getParameter("telephone");
        String joinDate = request.getParameter("joinDate");
        User user = new User();
        user.setUserId(UUID.randomUUID().toString());
        user.setEmail(email);
        user.setPassword(password);
        user.setUserName(userName);
        user.setDeptId(deptId);
        user.setDeptName(deptName);
        user.setGender(gender);
        user.setBirthday(birthday == null || birthday == "" ? null : Date.valueOf(birthday));
        user.setState(state == null || state == "" ? 0 : Long.parseLong(state));
        user.setTelephone(telephone);
        user.setJoinDate(joinDate == null || joinDate == "" ? null : Date.valueOf(joinDate));
        // 调用业务层
        userService.save(user);
        // 跳转回到页面
        request.getRequestDispatcher(request.getContextPath() + "/system/user?operation=list").forward(request, response);
    }

    // 删除用户
    private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 通过id查询用户是否关联角色
        String id = request.getParameter("id");
        List<User> userAndRole = findUserAndRole(id);
        // 判断是否有关联表
        if (userAndRole.size() == 0) {
            //调用service层
            userService.delete(id);
        } else {
            // 日志输出信息
            Log4jTest.logger.info("当前用户id为：" + id + "因为有关联的角色表，导致无法删除");
        }
        request.getRequestDispatcher(request.getContextPath() + "/system/user?operation=list").forward(request, response);
    }

    // 跳转到修改界面
    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 通过id查询用户信息
        String id = request.getParameter("id");
        User user = userService.findById(id);
        request.setAttribute("user", user);
        // 查询所有部门
        List<Dept> deptList = deptService.findAll();
        request.setAttribute("deptList", deptList);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/system/user/update.jsp").forward(request, response);
    }

    // 修改用户
    private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String userId = request.getParameter("id");
        String email = request.getParameter("email");
        String userName = request.getParameter("userName");
        String deptId = request.getParameter("deptId") == "" ? null : request.getParameter("deptId");
        // 通过deptId，查询到dept，然后获取deptName
        String deptName = null;
        if (deptId != null) {
            deptName = deptService.findById(deptId).getDeptName();
        }
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String state = request.getParameter("state");
        String telephone = request.getParameter("telephone");
        String joinDate = request.getParameter("joinDate");
        User user = new User();
        user.setUserId(userId);
        user.setEmail(email);
        user.setUserName(userName);
        user.setDeptId(deptId);
        user.setDeptName(deptName);
        user.setGender(gender);
        user.setBirthday(birthday == null || birthday == "" ? null : Date.valueOf(birthday));
        user.setState(state == null || state == "" ? 0 : Long.parseLong(state));
        user.setTelephone(telephone);
        user.setJoinDate(joinDate == null || joinDate == "" ? null : Date.valueOf(joinDate));
        // 调用服务层
        userService.updateUser(user);
        request.getRequestDispatcher(request.getContextPath() + "/system/user?operation=list").forward(request, response);
    }

    //查询用户，通过分页查询
    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String pageNum = request.getParameter("page");
        SystemSet systemSet = userService.findSystemSetByModuleName("user");
        String pageSize = systemSet.getPageSize();
        // 2.调用服务层
        PageInfo page = userService.findByPage(pageNum,pageSize);
        // 4.响应数据
        request.setAttribute("page", page);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/system/user/list.jsp").forward(request, response);
    }

    // 条件查询，动态查询，分页查询
    private void conditionSearch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageNum = request.getParameter("page");
        SystemSet systemSet = userService.findSystemSetByModuleName("user");
        String pageSize = systemSet.getPageSize();
        String searchUserName = request.getParameter("searchUserName");
        String searchEmail = request.getParameter("searchEmail");
        String searchDept = request.getParameter("searchDept");
        String searchState = request.getParameter("searchState");
        String searchGender = request.getParameter("searchGender");
        PageInfo page = userService.findUserByCondition(pageNum,pageSize,searchUserName,searchEmail,searchDept,searchState,searchGender);
        request.setAttribute("searchUserName",searchUserName);
        request.setAttribute("searchEmail",searchEmail);
        request.setAttribute("searchDept",searchDept);
//        request.setAttribute("searchState",searchState == null || searchState =="" ? 100 : searchState);
//        request.setAttribute("searchGender",searchGender == null || searchGender =="" ? 100 : searchGender);
        request.setAttribute("searchState",searchState == null || searchState =="" ? 100 : searchState);
        request.setAttribute("searchGender",searchGender == null || searchGender =="" ? 100 : searchGender);
        request.setAttribute("page", page);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/system/user/list.jsp").forward(request, response);
    }

    // 通过id查询用户关联的，一个用户对应一个部门，对应多个角色
    private List<User> findUserAndRole(String userId) {
        // 调用服务层
        List<User> userList = userService.findUserAndRole(userId);
        return userList;
    }

    // 显示用户及关联角色
    private void userRoleList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 查询所有的角色，通过id查询用户拥有的角色，拥有的角色返回remark
        String userId = request.getParameter("userId");
        User user = userService.findById(userId);
        List<Role> roleList = userService.userRoleList(userId);
        // 响应数据
        request.setAttribute("user",user);
        request.setAttribute("roleList", roleList);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/system/user/role.jsp").forward(request, response);

    }

    // 修改用户关联的角色
    private void updateRole(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userId = request.getParameter("userId");
        String[] roleIds = request.getParameterValues("roleIds");
        userService.updateRole(roleIds,userId);

        // 返回查询界面
        this.list(request,response);
    }
}